/**
 * 创元汇 - WebName
 * https://menger.me
 * @大梦
 */

import React, {Component} from 'react'
import {
    Text,
    View,
    Image,
    TextInput,
    ScrollView,
    StyleSheet,
    TouchableOpacity,
    StatusBar,
    WebView,
    Platform
} from 'react-native'
import AlertManager from '../../components/common/AlertManager'
import NetRequest from '../../utils/utilsRequest'
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'
import ServicesApi from '../../constants/ServicesApi'
import GlobalStyles from '../../constants/GlobalStyles'
import NavigationBar from '../../components/common/NavigationBar'
import UtilsView from '../../utils/utilsView'
import { toastShort, toastLong, consoleLog } from '../../utils/utilsToast'
import ModalDropdown from 'react-native-modal-dropdown'
import pingguItem from '../../assets/datajson/pingguItem.json'
import {Overlay, Label, Button} from 'teaset';
export default class Pinggu extends Component {

    constructor(props) {
        super(props);
        this.state =  {
            problemData: pingguItem.data,
            questionNum: pingguItem.data.length,
            problemActive: 0,
            answerActive: -1,
            resultAnswer: '',
            check_risk_info: 0,
            card_type: [
                {
                    id: 1,
                    name: '身份证'
                },
                {
                    id: 2,
                    name: '港澳通行证'
                },
                {
                    id: 3,
                    name: '护照'
                },
                {
                    id: 4,
                    name: '台湾居民来往大陆通行证'
                },
                {
                    id: 5,
                    name: '其他'
                },
            ],
            card_id: '',
            card_name: '',
            card_num: '',
            truename: '',
        }
        // this.netRequest = new NetRequest();
    }

    async componentWillMount(){
        try {
            await this.loadNetData();
        } catch (error) {
            // // console.log(error);
        }

    }

    componentDidMount(){
        
    }

    onBack = () => {
        this.props.navigation.state.params.onCallBack();
        this.props.navigation.goBack();
    }

    componentWillUnmount = () => {
        this.onBack();
    }

    updateState= (state) => {
        if (!this) { return };
        this.setState(state);
    }

    loadNetData = () => {
        // 判断是否填写了基本资料
        let url = ServicesApi.check_risk_info;
        let data = {
            member_id: global.user.userData.id,
            token: global.user.userData.token
        }

        Services.post(url, data, true)
            .then( result => {
                console.log(result);
                if (result && result.code == StatusCode.SUCCESS_CODE) {
                    // 基础资料完整
                    this.updateState({
                        check_risk_info: 1
                    })
                }else{
                    // 基础资料不完整
                    this.updateState({
                        check_risk_info: 0
                    })
                    // toastShort(result.msg);
                }
            })
            .catch( error => {
                // console.log(error);
                toastShort('服务器请求失败，请稍后重试！');
            })
    }

    selectThis = (j) => {
        this.setState({
            answerActive: j
        })
    }

    
    toSubmit = (type) => {
        if(this.state.answerActive == -1){
            toastShort('请作答本题之后再进行下一题');
            return false;
        }else{
            let thisAnswer = this.state.answerActive, resultAnswers = this.state.resultAnswer;
            if(thisAnswer == 0){
                thisAnswer = 'A';
            }else if(thisAnswer == 1){
                thisAnswer = 'B';
            }else if(thisAnswer == 2){
                thisAnswer = 'C';
            }else if(thisAnswer == 3){
                thisAnswer = 'D';
            }else if(thisAnswer == 4){
                thisAnswer = 'E';
            }

            // console.log('------------------------------');
            // console.log(this.state.resultAnswer);
            // console.log(thisAnswer);
            resultAnswers += thisAnswer + ',';
            // console.log(resultAnswers);

            if(type == 0){
                this.setState({
                    problemActive: this.state.problemActive+1,
                    answerActive: -1,
                    resultAnswer: resultAnswers
                })
            }else if(type == 1){
                resultAnswer = resultAnswers.substr(0,resultAnswers.length-1);
                // console.log(resultAnswer);
                // 提交
                let url = ServicesApi.insert_risk;
                let data = {
                    answer: resultAnswer,
                    member_id: global.user.userData.id,
                    token: global.user.userData.token,
                }
                Services.post(url, data, true)
                .then( result => {
                    console.log(result);
                    if (result && result.code == StatusCode.SUCCESS_CODE) {
                        if(result.data.risk_result == 0){
                            const params = {
                                title: '温馨提示',
                                detail: '尊敬的会员，您的测评得分'+result.data.risk_num+'分，暂无可匹配的风险等级产品，请点击“确认”返回测评问卷进行检查。',
                                actions: [
                                    { title: '取消', titleStyle: {  }, actionStyle: {  }, onPress: () => { 
                                        
                                    } },
                                    { title: '确认', onPress: () => { 
                                        this.setState({
                                            problemActive: 0,
                                            answerActive: -1,
                                            resultAnswer: ''
                                        })
                                    } }
                                ]
                            }
                            AlertManager.show(params)
                            
                        }else{
                            // toastShort('您的评估结果为'+result.data.risk_msg+'，已通过本评估', 5000);
                            const params = {
                                title: '温馨提示',
                                detail: '尊敬的会员，您的测评得分'+result.data.risk_num+'分，在售产品风险等级均与您的风险等级匹配，请点击“确认”进行签署风险测评问卷。',
                                actions: [
                                    { title: '取消', titleStyle: {  }, actionStyle: {  }, onPress: () => { 
                                        
                                    } },
                                    { title: '确认', onPress: () => { 
                                        this.pingguAgree(result.data.url, result.data.show_url);
                                    } }
                                ]
                            }
                            AlertManager.show(params)
                            
                            // this.onPushNavigator('RenzhengTypeLogin');
                        }
                    }else{
                        toastLong(result.msg);
                    }
                })
                .catch( error => {
                    // toastShort('服务器请求失败，请稍后重试！');
                })
                
            }
        }    
        
    }

    pingguAgree = (shuju, show_link) => {
        let overlayView = (
            <Overlay.PullView side='bottom' modal={false} ref={v => this.overlayView = v}>
                <View style={{backgroundColor: '#fff', width: GlobalStyles.width, height: GlobalStyles.height}}>
                    <WebView
                        startInLoadingState={true}
                        source={{uri: show_link}}
                        style={styles.webContainer}
                    />
                    
                    <View style={styles.botBar}>
                        <TouchableOpacity onPress={()=>{this.overlayView && this.overlayView.close()}} style={styles.botLeft}>
                            <Text style={[styles.botLeftText, {fontSize: 15}]}>取消</Text>
                        </TouchableOpacity>
                        <TouchableOpacity onPress={()=>{this.submit001(shuju);}} style={styles.botRight}>
                            <Text style={styles.botRightText}>同意签署</Text>
                        </TouchableOpacity> 
                    </View>
                </View>
            </Overlay.PullView>
        );
        Overlay.show(overlayView);
    }

    submit001 = (shuju) => {
        let url = ServicesApi.create_pdf;
        let data = {
            url: shuju,
            style: '001',
            id: '',
            member_id: global.user.userData.id,
            token: global.user.userData.token,
        }
        AlertManager.showPopView(<View style={[GlobalStyles.loadingview, GlobalStyles.flexColumnCenter]}><Image source={require('../../assets/images/icons/loading.gif')} style={GlobalStyles.loading} /><Text style={GlobalStyles.loadingtext}>文件生成中，请稍候...</Text></View>, { modal:true })
        Services.post(url, data, true)
        .then( result => {
            console.log(result);
            AlertManager.hide();
            if (result && result.code == StatusCode.SUCCESS_CODE) {
                const params = {
                    title: '温馨提示',
                    detail: '尊敬的会员，您已成功签署风险测评问卷，请点击“继续”，进行签署《符合合格投资者标准的承诺书》。',
                    actions: [
                        { title: '取消', titleStyle: {  }, actionStyle: {  }, onPress: () => { 
                            this.overlayView && this.overlayView.close()
                        } },
                        { title: '继续', onPress: () => { 
                            this.onPushNavigator('RenzhengchengnuoLogin');
                            this.overlayView && this.overlayView.close()
                        } }
                    ]
                }
                AlertManager.show(params)
            }else{
                toastLong(result.msg);
            }
        })
        .catch( error => {
            // toastShort('服务器请求失败，请稍后重试！');
        })
    }

    onPushNavigator = (compent) => {
        const { navigate } = this.props.navigation;
        navigate( compent , {
            
        })
    }

    // 证件类型
    renderCardRow = (rowData) => {
        return (
            <View style = {GlobalStyles.dropdownRow}>
                <Text style = {GlobalStyles.dropdownRowText}>{rowData.name}</Text>
            </View>
        );
    }

    renderCardButtonText = (rowData) => {
        const {id, name} = rowData;
        this.setState({
            card_id: id,
            card_name: name
        })
        return name;
    }

    toStart = () => {
        let url = ServicesApi.perfect_risk_info;
        let truename = this.state.truename,
            card_id = this.state.card_id,
            card_num = this.state.card_num;

        if(!truename){toastShort('请填写真实姓名');return false;}
        if(!card_id){toastShort('请选择证件类型');return false;}
        if(!card_num){toastShort('请填写证件号');return false;}

        let data = {
            truename: truename,
            card_type: card_id,
            card_num: card_num,
            member_id: global.user.userData.id,
            token: global.user.userData.token
        }

        Services.post(url, data, true)
            .then( result => {
                console.log(result);
                if(result && result.code == StatusCode.SUCCESS_CODE){
                    toastShort(result.msg);
                    this.updateState({
                        check_risk_info: 1
                    })
                }else{
                    toastLong(result.msg);
                }
            })
            .catch( error => {
                // consoleLog('链接服务器出错，请稍后重试', error);
            })
    }

    render(){
        let navigationBar = {
            backgroundColor: '#fff',
            borderBottomColor: '#f2f2f2',
            borderBottomWidth: 1
        }
        return (
            <View style={styles.container}>
                <NavigationBar
                    title = {'风险承受能力评估'}
                    style = {navigationBar}
                    titleStyle = {{color: '#333333'}}
                    leftButton = {UtilsView.getLeftBlackButton(() => this.onBack())}
                />
                <StatusBar
                    animated = {true}
                    hidden = {false}
                    backgroundColor = {'transparent'}
                    translucent = {true}
                    barStyle = {'dark-content'}
                />
                {this.state.check_risk_info == 0 ?
                    <KeyboardAwareScrollView style={[GlobalStyles.whiteModule, {marginTop: 10}]} keyboardShouldPersistTaps={'handled'}>
                        <Text style={[GlobalStyles.defaultText, {fontSize: 13, color: '#666'}]}>根据评估结果，您的风险承受能力将属于以下五种类型中的一种：<Text style={{color: GlobalStyles.themeColor}}>保守型、稳健型、平衡型、成长型、进取型。</Text>为了给您提供更好的服务，请认真作答，感谢配合！</Text>
                        <Text style={[GlobalStyles.defaultText, {fontSize: 13, color: '#666'}]}>风险承受能力评估之前需要先完善下个人基本资料！</Text>
                    
                        <View style={[GlobalStyles.whiteModule, {marginTop: 10}]}>
                            <View style={GlobalStyles.mcell}>
                                <View style={GlobalStyles.cellItem}>
                                    <Text style={GlobalStyles.cellLeft}>真实姓名</Text>
                                    <View style={GlobalStyles.cellRight}>
                                        <TextInput
                                            placeholder={this.state.truename ? this.state.truename : '请填写真实姓名'}
                                            onChangeText={(text) => {
                                                this.updateState({
                                                    truename: text
                                                })
                                            }}
                                            style={[GlobalStyles.cellInput, GlobalStyles.cellTextColor, GlobalStyles.isIOS ? null : styles.inputAndroid]} 
                                            underlineColorAndroid={'transparent'}
                                        >
                                        </TextInput>
                                    </View>
                                </View>
                                <View style={GlobalStyles.cellItem}>
                                    <Text style={GlobalStyles.cellLeft}>证件类型</Text>
                                    <View style={GlobalStyles.cellRight}>
                                        <ModalDropdown
                                            style = {[GlobalStyles.selectView, {width: 160}]}
                                            textStyle = {[GlobalStyles.textStyle, {width: 160}]}
                                            dropdownStyle = {[GlobalStyles.dropdownStyle, {width: 160, height: 200}]}
                                            defaultValue = {'请选择'} 
                                            renderRow={this.renderCardRow.bind(this)}
                                            options = {this.state.card_type}
                                            renderButtonText = {(rowData) => this.renderCardButtonText(rowData)}
                                        >
                                            <View style={[GlobalStyles.selectViewWrap, {width: 160}]}>
                                                <View style={[GlobalStyles.paymentMethodTitleView, {width: 160}]}>
                                                    <Text style={GlobalStyles.cargoAttributesTitle}>{this.state.card_name ? this.state.card_name : '请选择'}</Text>
                                                </View>
                                            </View>
                                        </ModalDropdown>
                                    </View>
                                </View>
                                <View style={GlobalStyles.cellItem}>
                                    <Text style={GlobalStyles.cellLeft}>证件号</Text>
                                    <View style={GlobalStyles.cellRight}>
                                        <TextInput
                                            placeholder={this.state.card_num ? this.state.card_num : '请填写证件号'}
                                            onChangeText={(text) => {
                                                this.updateState({
                                                    card_num: text
                                                })
                                            }}
                                            style={[GlobalStyles.cellInput, GlobalStyles.cellTextColor, GlobalStyles.isIOS ? null : styles.inputAndroid]} 
                                            underlineColorAndroid={'transparent'}
                                        >
                                        </TextInput>
                                    </View>
                                </View>
                            </View>
                        </View>

                        <TouchableOpacity onPress={()=>this.toStart()} style={[GlobalStyles.submit, {marginTop: 15}]}>
                            <View style={GlobalStyles.btn}>
                                <Text style={GlobalStyles.btna}>开始测评</Text>
                            </View>
                        </TouchableOpacity>
                        

                        <View style={[GlobalStyles.tishiItem]}>
                            <Text style={[GlobalStyles.tishititle, {marginTop: -5, marginBottom: 8}]}>温馨提示</Text>
                            <Text style={[GlobalStyles.tishitext, {fontSize: 13, color: '#787878'}]}>私募基金投资需承担各类风险，本金可能遭受损失。同时，私募基金投资还要考虑市场风险、信用风险、流动性风险、操作风险等各类投资风险。您在基金认购过程中应当注意核对自己的风险识别和风险承受能力，选择与自己风险识别能力和风险承受能力相匹配的私募基金。</Text>
                        </View>
                    </KeyboardAwareScrollView>
                :
                    <ScrollView style={[GlobalStyles.whiteModule, {marginTop: 10}]}>
                        <Text style={[GlobalStyles.defaultText, {fontSize: 13, color: '#666'}]}>根据评估结果，您的风险承受能力将属于以下五种类型中的一种：<Text style={{color: GlobalStyles.themeColor}}>保守型、稳健型、平衡型、成长型、进取型。</Text>为了给您提供更好的服务，请认真作答，感谢配合！</Text>
                        <View style={[styles.pingguModule]}>
                            {this.renderProblem(this.state.problemData)}
                        </View>
                        <View style={[styles.numItem, GlobalStyles.flexRowCenter]}>
                            <Text style={[styles.numNow, styles.numSame]}>{this.state.problemActive+1}</Text>
                            <Text style={[styles.numXian, styles.numSame]}> / </Text>
                            <Text style={[styles.numAll, styles.numSame]}>13</Text>
                        </View>
                        
                        {this.state.problemActive == this.state.problemData.length-1 ? 
                            <TouchableOpacity onPress={()=>this.toSubmit(1)} style={[GlobalStyles.submit, {marginTop: 15}]}>
                                <View style={GlobalStyles.btn}>
                                    <Text style={GlobalStyles.btna}>提交</Text>
                                </View>
                            </TouchableOpacity>
                            :
                            <TouchableOpacity onPress={()=>this.toSubmit(0)} style={[GlobalStyles.submit, {marginTop: 15}]}>
                                <View style={GlobalStyles.btn}>
                                    <Text style={GlobalStyles.btna}>下一题</Text>
                                </View>
                            </TouchableOpacity>
                        }
                        

                        <View style={[GlobalStyles.tishiItem]}>
                            <Text style={[GlobalStyles.tishititle, {marginTop: -5, marginBottom: 8}]}>温馨提示</Text>
                            <Text style={[GlobalStyles.tishitext, {fontSize: 13, color: '#787878'}]}>私募基金投资需承担各类风险，本金可能遭受损失。同时，私募基金投资还要考虑市场风险、信用风险、流动性风险、操作风险等各类投资风险。您在基金认购过程中应当注意核对自己的风险识别和风险承受能力，选择与自己风险识别能力和风险承受能力相匹配的私募基金。</Text>
                        </View>
                    </ScrollView>
                }
            </View>
        );
    }

    renderProblem(data){
        let problem = [];
        for (var i = 0; i < data.length; i++) {
            if(this.state.problemActive == i){
                var problemStyle = [styles.pingguItem, styles.pingguItemActive];
            }else{
                var problemStyle = [styles.pingguItem];
            }
            let problemItem = (
                <View key={i} style={problemStyle}>
                    <Text style={styles.pingguTitle}>{data[i].id}. {data[i].title}</Text>
                    <View style={[GlobalStyles.mradio, {width: GlobalStyles.width-60, marginLeft: 0}]}>
                        {this.renderAnswer(data[i])}
                    </View>
                </View>    
            )
            problem.push(problemItem);
        }
        return problem;
    }

    renderAnswer(data){
        let answer = [];

        for (var j = 0; j < data.length; j++) {
            let thisid = j;
            let answerItem = (
                <TouchableOpacity key={j} onPress={()=>{this.selectThis(thisid)}} style={[GlobalStyles.radioItem, GlobalStyles.flexRowStartStart, {width: GlobalStyles.width-60}]}>
                    <View style={GlobalStyles.radioLeft}>
                        {this.state.answerActive == j ? <View style={GlobalStyles.radioActive}></View> : null}
                    </View>
                    <Text style={[GlobalStyles.radioRightThemeColor, {width: GlobalStyles.width-60-24}]}>{data.answer[j].wenzi}  {data.answer[j].fenshu}</Text>
                </TouchableOpacity>
            )
            answer.push(answerItem);
        }
        return answer;
    }





}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: GlobalStyles.bgColor,
    },
    webContainer: {
        width: GlobalStyles.width,
        height: GlobalStyles.height,
        flex: 1,
        backgroundColor: '#fff',
        marginTop: Platform.OS === 'ios' ? -15 : 0,
    },
    pingguModule: {
        borderWidth: 1,
        borderColor: '#ececec',
        margin: 15,
        marginBottom: 10,
        borderRadius: 5,
        padding: 15

    },
    pingguItem: {
        display: 'none',
        width: GlobalStyles.width - 60,

    },
    pingguItemActive: {
        display: 'flex'
    },
    pingguTitle: {
        color: GlobalStyles.themeColor,
        fontSize: 16,
        lineHeight: 22,
    },
    numItem: {

    },
    numNow: {

    },
    numXian: {

    },
    numAll: {

    },
    numSame: {
        color: GlobalStyles.themeColor,
        fontSize: 14,

    },
    botBar: {
        height: 54,
        backgroundColor: '#fff',
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        borderTopColor: '#ececec',
        borderTopWidth: 1,

    },
    botLeft: {
        height: 54,
        flex: 1,
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center'
    },
    botLeftIco: {
        height: 24,

    },
    botLeftText: {
        fontSize: 13,
        color: '#666',
        height: 20,
        lineHeight: 20,
    },
    botRight: {
        flex: 2.5,
        backgroundColor: GlobalStyles.themeColor,
        height: 54,
        justifyContent: 'center',
        alignItems: 'center',

    },
    botRightText: {
        color: '#fff',
        fontSize: 18,
        fontWeight: 'bold'
    },
});
